package com.xiaxiang.xiawan.Home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dg.acb.utils.configdata.XXConstants;
import com.third.share.ShareData;
import com.xiaxiang.xiawan.R;
import com.xiaxiang.xiawan.Util.XXToolUtil;
import com.xiaxiang.xiawan.XXConfigData;
import com.xiaxiang.xiawan.XXMainApplication;
import com.xiaxiang.xiawan.share.ShareTest;
import com.xiaxiang.xiawan.share.XXShareDialog;
import com.xiaxiang.xiaxwan.ar.data.XXARMaterialVideoData;
import com.xx.xiawan.net.DGJsonPutRequest;
import com.xx.xiawan.net.DGJsonRequest;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGRequestListener;
import com.xx.xiawan.net.GetRequest;
import com.xx.xiawan.videoplayer.Utils;
import com.xx.xiawan.videoplayer.VideoActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2017-11-08.
 */
//com.xiaxiang.xiawan.Home.XXARVideoActivity
public class XXARVideoActivity extends VideoActivity {
    private XXShareDialog shareDialog;
    private XXMainApplication mMainApplication;
    protected XXARMaterialVideoData mMaterialData;
    private final static int START_PLAYER = 0;
    private final static int START_LIKE = 1;
    private int mStyle = START_PLAYER;
    private Handler mUiHandler;
    private ImageView imgLike;
    private TextView tvShareCount;
    private TextView tvLikeCount;
    private final static int SHARE_COUNT = 1;
    private final static int LIKE_COUNT = 2;
    private final static int INIT_DATA = 3;

    public void onCreate(Bundle bundle) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mMainApplication = (XXMainApplication) getApplication();
        mMainApplication.initUserInfo();
        super.onCreate(bundle);
        shareDialog = new XXShareDialog(this);
        if ((mMaterialData.mMaterialUrl == null || mMaterialData.mMaterialUrl.length() == 0)
                || (mMaterialData.mMaterialId == null || mMaterialData.mMaterialId.length() == 0)) {
            Button btnPlayer = (Button) this.findViewById(R.id.btnPlayer);
            btnPlayer.setVisibility(View.INVISIBLE);
        }
    }

    private void getInitData() {
        DGRequestListener listener = new DGRequestListener() {
            @Override
            public void onSuccess(DGJsonResult result) {
                sendMessage(INIT_DATA, result.result);
            }

            @Override
            public void onError(String error) {
                Log.e("by", " getVideo error is " + error);
            }
        };
        StringBuilder builder = new StringBuilder();
        String dy = "=";
        String a = "&";
        builder.append(XXConstants.HTTP_GET_VIDEO_BY_ID);
        builder.append("?");
        builder.append("id");
        builder.append(dy);
        builder.append(mMaterialData.mVideoId);
        builder.append(a);
        builder.append("materialId");
        builder.append(dy);
        builder.append(mMainApplication.getMachineId());
        GetRequest getRequest = new GetRequest(builder.toString(), this, listener);
        String token = mMainApplication.getToken();
        if (mMainApplication.getIsLogin()) {
            getRequest.header(XXConfigData.TOKEN_KEY, token);
        }
        getRequest.startNoLock();
    }

    private void initUiHandler() {
        mUiHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case SHARE_COUNT:
                        break;
                    case LIKE_COUNT:
                        tvLikeCount.setText("" + msg.arg1);
                        break;

                    case INIT_DATA:
                        String res = (String) msg.obj;
                        Log.e("by", " DGJsonResult result is " +res);
                        try {
                            JSONObject jsonObject = new JSONObject(res);
                            int likeCount = jsonObject.getInt("likeCount");
                            int readCount = jsonObject.getInt("readCount");
                            boolean ifLiked = jsonObject.getBoolean("ifLiked");
                            tvLikeCount.setText("" + likeCount);
                            tvShareCount.setText("" + readCount);
                            if (ifLiked){
                                imgLike.setImageResource(R.mipmap.home_heart_click);
                            }else {
                                imgLike.setImageResource(R.mipmap.home_heart);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        break;

                    default:
                        break;
                }
            }
        };
    }

    protected void init() {
        setContentView(R.layout.act_video_layout);
        initUiHandler();
        initView();
        Intent intent = getIntent();
        if (intent != null) {
            mMaterialData = intent.getParcelableExtra("arMaterialVideoData");
            if (mMaterialData != null) {
                mVideoPath = mMaterialData.mVideoPath;
                getInitData();
                ImageView imgHead = (ImageView) findViewById(R.id.imgHead);
                final WeakReference<ImageView> imageViewWeakReference = new WeakReference<ImageView>(imgHead);
                ImageView weekImage = imageViewWeakReference.get();
                Log.e("ho", " mMaterialData.mHeadPhoto is " + mMaterialData.mHeadPhoto);
                if ( mMaterialData.mHeadPhoto !=null &&  mMaterialData.mHeadPhoto.length()>0) {
                    Glide.with(this).load(mMaterialData.mHeadPhoto).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(weekImage).onLoadFailed(getResources().getDrawable(R.mipmap.home_head));
                }else {
                    weekImage.setImageResource(R.mipmap.home_head);
                }
                TextView tvProductionName = (TextView) findViewById(R.id.tvProductionName);
                TextView tvUserName = (TextView) findViewById(R.id.tvVideoName);
                tvProductionName.setText(mMaterialData.mName);
                tvUserName.setText(mMaterialData.mUserName);
            }
        }
        initVideo();
    }

    protected void initView() {
        Button btnPlayer = (Button) this.findViewById(R.id.btnPlayer);
        btnPlayer.setOnClickListener(this);
        ImageView imgShare = (ImageView) this.findViewById(R.id.imgShare);
        imgShare.setOnClickListener(this);
        imgLike = (ImageView) this.findViewById(R.id.imgLike);
        imgLike.setOnClickListener(this);
        ImageView imgBack = (ImageView) this.findViewById(R.id.imgBack);
        imgBack.setOnClickListener(this);

        tvShareCount = (TextView) this.findViewById(R.id.tvShareCount);
        tvLikeCount = (TextView) this.findViewById(R.id.tvLikeCount);
        imgBack.setImageResource(R.mipmap.left_light_back);

    }

    protected XXARMaterialVideoData getmMaterialData() {
        return mMaterialData;
    }

    protected void startShare() {
        ShareData shareData = new ShareData();

        //  shareData.mShareUrl = XXToolUtil.videourl;
        shareData.mShareUrl = mMaterialData.mVideoPath;
        shareData.mThumbFileUrl = mMaterialData.mThumbnailUrl;
        //shareData.mBitmap = null;
        shareData.mShareTitle = getString(R.string.ar_video);
        shareData.mShareStyle = ShareTest.VIDEO11;
        shareDialog.setShareData(shareData);
        shareDialog.showDialog();
    }

    protected void pressPlayerBtn() {
        if (mMainApplication.getIsLogin()) {
            startPlayer();
        } else {
            startLogin();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XXConfigData.LOGIN_REQUEST_CODE) {
            if (resultCode == XXConfigData.LOGIN_RECODE_SUCCESS) {
                mMainApplication.initUserInfo();
                if (mStyle == START_PLAYER) {
                    startPlayer();
                } else if (mStyle == START_LIKE) {
                    startLike();
                }
            }
        }
    }

    protected void startPlayer() {
        Intent intent = new Intent("com.xiaxiang.xiawan.ar.camera");
        intent.setPackage(getPackageName());
        if (mMaterialData != null) {
            intent.putExtra(Utils.MATERIAL_VIDEO_DATA_KEY, mMaterialData);
            intent.putExtra(XXARMaterialVideoData.AR_MODE_KEY, mMaterialData.mArMode);
        } else {
            intent.putExtra(XXARMaterialVideoData.AR_MODE_KEY, 1);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
    }

    protected void onMyClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btnPlayer:
                mStyle = START_PLAYER;
                pressPlayerBtn();
                break;
            case R.id.imgBack:
                finish();
                break;
            case R.id.imgShare:
                startShare();
                break;
            case R.id.imgLike:
                imgLike.setImageResource(R.mipmap.home_heart_click);
                mStyle = START_LIKE;
                startLike();
                break;
        }
    }

    private void startLogin() {
        Intent intent = new Intent("com.xiaxiang.xiawan.login");
        intent.setPackage(getPackageName());
        startActivityForResult(intent, XXConfigData.LOGIN_REQUEST_CODE);
    }

    private void startLike() {
        final JSONObject jsonObject = new JSONObject();
        String token = mMainApplication.getToken();
        try {
            jsonObject.put("video_id", mMaterialData.mVideoId);
            jsonObject.put("machine_id", mMainApplication.getMachineId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        DGRequestListener listener = new DGRequestListener() {
            @Override
            public void onSuccess(DGJsonResult result) {
                Log.e("like", " like result is " + result.result);
                try {
                    JSONObject jsonObject1 = new JSONObject(result.result);
                    int likeCount = jsonObject1.getInt("likeCount");
                    sendMessage(LIKE_COUNT, likeCount);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String error) {
                Log.e("like", " like onError is " + error);
            }
        };

        DGJsonPutRequest jsonPutRequest = new DGJsonPutRequest(this, XXConstants.HTTP_LIKE_DATA_URL, jsonObject, listener);
        if (mMainApplication.getIsLogin()) {
            jsonPutRequest.header(XXConfigData.TOKEN_KEY, token);
        }
        jsonPutRequest.startNoLock();
    }

    private void sendMessage(int what, Object obj) {
        Message msg = mUiHandler.obtainMessage();
        msg.what = what;
        if (obj != null)
            msg.obj = obj;
        mUiHandler.sendMessage(msg);
    }

    private void sendMessage(int what, int obj) {
        Message msg = mUiHandler.obtainMessage();
        msg.what = what;
        msg.arg1 = obj;
        mUiHandler.sendMessage(msg);
    }
}
